package com.simple.puzzle;

import android.graphics.Bitmap;
import android.graphics.Matrix;

public class Picture {
	static final int DEFAULT_DEVIDE_VALUE = 200;
	static final int DEFAULT_WIDTH = 600;
	static final int DEFAULT_HEIGHT = 800;
	static final int DEFAULT_X = 3;
	static final int DEFAULT_Y = 4;
	Bitmap picture;

	Bitmap portion[];
	int width;
	int height;
	int x;
	int y;
	int devide_value;
	int devide_value_width;
	int devide_value_heigh;

	public Picture(Bitmap picture) {
		// TODO Auto-generated constructor stub
		this.picture = scale(picture, DEFAULT_WIDTH, DEFAULT_HEIGHT);
		x = DEFAULT_X;
		y = DEFAULT_Y;
		devide_value = DEFAULT_DEVIDE_VALUE;
		devide_value_heigh = devide_value;
		devide_value_width = devide_value;

		portion = new Bitmap[x * y + 1];
	}

	/**
	 * devide to x * y
	 * 
	 * @param picture
	 * @param swidth
	 * @param sheight
	 * @param x
	 * @param y
	 */
	public Picture(Bitmap picture, int swidth, int sheight, int x, int y) {
		this.picture = scale(picture, swidth, sheight);
		portion = new Bitmap[x * y + 1];
		this.x = x;
		this.y = y;
		devide_value_width = swidth / x;
		devide_value_heigh = sheight / y;
	}

	/**
	 * scale image
	 */
	public Bitmap scale(Bitmap bitmap, int newwidth, int newheight) {
		int iwidth = bitmap.getWidth();
		int iheight = bitmap.getHeight();

		float scaleWidth = ((float) newwidth) / iwidth;
		float scaleHeight = ((float) newheight) / iheight;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		return Bitmap
				.createBitmap(bitmap, 0, 0, iwidth, iheight, matrix, false);
	}

	/**
	 * devide 3 x 4
	 */
	public void devidePicture() {
		for (int i = 0; i < x; i++) {
			for (int j = 0; j < y; j++) {
				int w = i * devide_value_width;
				int h = j * devide_value_heigh;
				Bitmap bit = Bitmap.createBitmap(picture, w, h, devide_value_width,
						devide_value_heigh);
				portion[j * x + i] = bit;
			}
		}
	}

	public Bitmap[] getDevidedPortion() {
		devidePicture();
		return portion;
	}
}
